﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using PPI.Data.Inspection;
using PPI.Entities.Inspections;
using VMind.Global;

namespace PPI.ServiceLogic.Inspections
{
    public class LInspectionImage
    {
        public static DataSet GetImagesByInspection(Int32 inspectionId, string connectionKey)
        {
            return DInspectionImage.SelectAll(connectionKey, inspectionId);
        }

        public static List<EInspectionImage> GetByInspection(string connectionKey, Int32 inspectionId)
        {
            DataTable dt = DInspectionImage.SelectAll(connectionKey,inspectionId).Tables[0];
            return ParseDatatableImages(dt);
        }

        private static List<EInspectionImage> ParseDatatableImages(DataTable dt)
        {
            List<EInspectionImage> _InspectionImages = new List<EInspectionImage>();

            foreach (DataRow dr in dt.Rows)
            {
                EInspectionImage _Image = new EInspectionImage();
                _Image.Id = ConvertHelper.ToInt32(dr["Vendor_InspVisit_XmissionStructures_ImageId"]);
                _Image.Inspection.Id = ConvertHelper.ToInt32(dr["Vendor_InspVisit_XMissionStructure_PoleFk"]);
                _Image.InspectionResult.Id = ConvertHelper.ToInt32(dr["Vendor_InspVisit_XmissionStructures_ResultFk"]);
                _Image.FileName = dr["filename"].ToString();
                _InspectionImages.Add(_Image);

            }
            return _InspectionImages;
        }

        public static Int32 Save(Int32 imageId,Int32 InspectionFk, Int32 InspectionResultFk, string filename, string connectionKey)
        {
            Int32 returnId = imageId;
            if (imageId == Int32.MinValue)
                returnId = Insert(InspectionFk,InspectionResultFk,filename,connectionKey);

            return returnId;

        }

        private static Int32 Insert(Int32 InspectionFk, Int32 InspectionResultFk, string filename, string connectionKey)
        {
            Int32 newImageId = DInspectionImage.Insert(InspectionFk, InspectionResultFk, filename, connectionKey);

            string FileName = InspectionFk + "_" + newImageId + ".jpg";
            DInspectionImage.UpdateFileName(newImageId, FileName, connectionKey);
            return newImageId;
        }


        public static void Delete(Int32 imageId, string fileName, string connectionKey)
        {
            DInspectionImage.Delete(imageId,connectionKey);
        }
    }
}
